﻿using NineSeas.Models;
using NineSeas.Services;
using Orchard.ContentManagement.Drivers;
namespace NineSeas.Drivers
{
    public class ChapterDriver : ContentPartDriver<ChapterPart>
    {
        private readonly IChapterService _chapterService;
        public ChapterDriver(IChapterService chapterService)
        {
            _chapterService = chapterService;
        }
        protected override DriverResult Display(ChapterPart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_Chapter",
                () => shapeHelper.Parts_Chapter(
                        Chapter: part
                    ));
        }

        protected override DriverResult Editor(ChapterPart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_Chapter_Edit",
                () => shapeHelper.EditorTemplate(
                    TemplateName: "Parts/Chapter",
                    Model: part,
                    Prefix: Prefix));
        }

        protected override DriverResult Editor(ChapterPart part, Orchard.ContentManagement.IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);

            if (!part.SortOrder.HasValue)
            {
                var lastOrder = _chapterService.GetLastOrder(part.BookId);
                if (!lastOrder.HasValue || lastOrder.Value < -1) lastOrder = -1;

                part.SortOrder = lastOrder + 1;
            }

            return Editor(part, shapeHelper);
        }
    }
}